#include <WiFiManager.h> 
#include <Pinger.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <EEPROM.h>
#include <SimpleDHT.h>


int button = 0;
int pinDHT11 = 2;                  //IO2

char mqtt_server[40];
char mqtt_port[6] = "1883";
bool shouldSaveConfig = false;
int data;

WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6);
static SimpleDHT11 dht11(pinDHT11);


void configModeCallback (WiFiManager *myWiFiManager);
void ReConfigWIFI(bool isConfig);
bool CheckMQTTValid(char *mqtt_ip, uint8_t mqtt_ip_len, char* mqtt_port, uint8_t mqtt_port_len);



void setup() {
    bool ret;
    WiFiManager wifiManager;
    EEPROM.begin(256);
    data = EEPROM.read(0);
    Serial.printf("last_data : %d",data);

    data = data + 1;
    EEPROM.write(0, data);
    EEPROM.commit(); 

    pinMode(button, INPUT);
    Serial.begin(9600);
    WiFi.mode(WIFI_STA);

    wifiManager.addParameter(&custom_mqtt_server);
    wifiManager.addParameter(&custom_mqtt_port);

    wifiManager.autoConnect("AutoConnectAP");


    if (!wifiManager.autoConnect("AutoConnectAP", "password")) {
      Serial.println("failed to connect and hit timeout");
      delay(3000);
      //reset and try again, or maybe put it to deep sleep
      ESP.restart();
      delay(5000);
  }


    // WiFi连接成功后将通过串口监视器输出连接成功信息 
    Serial.println(""); 
    Serial.print("ESP8266 Connected to ");
    Serial.println(WiFi.SSID());              // WiFi名称
    Serial.print("IP address:\t");
    Serial.println(WiFi.localIP());           // IP


    Serial.println("connected...yeey :)");


    strcpy(mqtt_server, custom_mqtt_server.getValue());
    strcpy(mqtt_port, custom_mqtt_port.getValue());
    Serial.println("The values in the file are: ");
    Serial.println("\tmqtt_server : " + String(mqtt_server));
    Serial.println("\tmqtt_port : " + String(mqtt_port));

    ret = CheckMQTTValid(mqtt_server, strlen(mqtt_server), mqtt_port, strlen(mqtt_port));
    if(ret == true)
    {
      Serial.println("MQTT IP Config OK");
    }
    else
    {
      Serial.println("MQTT IP Config Error");
      ReConfigWIFI(true);
    }

}

void loop() {
  // if(digitalRead(button) == LOW)
  // {
  //   delay(100);
  //   if(digitalRead(button) == LOW)
  //   {
  //     Serial.println("Reconfig");
  //     ReConfigWIFI(true);
  //   }
  // }
  delay(1);
}


bool CheckMQTTValid(char *mqtt_ip, uint8_t mqtt_ip_len, char* mqtt_port, uint8_t mqtt_port_len)
{
  bool ret = false;
  Pinger pinger;

  if(mqtt_ip == NULL || mqtt_port == NULL || mqtt_ip_len == 0 || mqtt_port_len == 0)
  {
    return false;
  }


  ret = pinger.Ping(mqtt_ip);

  if(ret)
  {
    Serial.println("ping success.");
  }
  else
  {
    Serial.println("ping fail.");
  }

  return ret;
}

void configModeCallback (WiFiManager *myWiFiManager) 
{
  Serial.println("Entered config mode");
  Serial.println(WiFi.softAPIP());
  Serial.println(myWiFiManager->getConfigPortalSSID());
}

void ReConfigWIFI(bool isConfig)
{
  WiFiManager wm;
  if(isConfig == false) return ;
  wm.resetSettings();
  wm.setConfigPortalTimeout(300);
  wm.addParameter(&custom_mqtt_server);
  wm.addParameter(&custom_mqtt_port);
  if (!wm.startConfigPortal("OnDemandAP")) {
    Serial.println("failed to connect and hit timeout");
    delay(3000);
    Serial.println("Restart...");
    //reset and try again, or maybe put it to deep sleep
    ESP.restart();
    delay(5000);
  }

  Serial.println("connected...yeey :)");
}

void read_dht11(float *temp, float *humiti)
{
    byte temperature = 0;
    byte humidity = 0;
    int err = SimpleDHTErrSuccess;
    if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
        Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
        return;
    }

    Serial.print((int)temperature); Serial.print(" *C, "); 
    Serial.print((int)humidity); Serial.println(" H");
    delay(1500);
}